import * as types from "../types/cart.types";

const initialState = {
  cart: [],
};

export default function cartReducer(state = initialState, action) {
  switch (action.type) {
    // 保存购物车列表
    case types.SAVE_TO_CART:
      return {
        ...state,
        cart: action.payload,
      };
    // 更改商品数量
    case types.UPDATE_GOODS_COUNT:
      return {
        ...state,
        cart: state.cart.map((item) => {
          if (item.id === action.payload.id) {
            return { ...item, count: action.payload.count };
          }
          return item;
        }),
      };
    // 删除商品
    case types.DELETE_GOODS:
      return {
        ...state,
        cart: state.cart.filter((item) => item.id !== action.payload),
      };
    default:
      return state;
  }
}
